<!DOCTYPE html>
<html>
<head>
	<title>聊天室</title>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="public/expands/layui/css/layui.css">
	<link rel="stylesheet" type="text/css" href="public/css/chat.css">
</head>
<body>
	<div class="layui-container">
	  	<div class="layui-row">
		    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
		      	<div class="he_xin_code">
		      		<!-- 操作列 -->
		      		<div class="layui-col-xs1 layui-col-sm1 layui-col-md1 action_col">
		      			<!-- 当前用户头像 -->
		      			<div class="self_headpic">
		      				<div class="self_headpic_child_div">
		      					<img class="layui-circle" src="public/images/headpic/self.jpg">
		      				</div>
		      			</div>
		      			<!-- 通讯列表图标 -->
		      			<div class="mailing_list_icon">
		      				<div class="mailing_list_icon_child_div">
		      					<a><i class="layui-icon layui-icon-user"></i></a>
		      				</div>
		      			</div>
		      		</div>
		      		<!-- 聊天人员记录列表 -->
		      		<div class="layui-col-xs3 layui-col-sm3 layui-col-md3 chat_list">
		      			<div class="layui-card chat_list_child_div">
						  	<div class="layui-card-header user_div">
						  		<div class="layui-col-md3">
						  			<div class="user_headpic">
						  				<img src="public/images/headpic/self.jpg">
						  			</div>
						  		</div>
						  		<div class="layui-col-md7">
						  			<div class="user_nickname">长治拼车群</div>
						  		</div>
						  		<div class="layui-col-md2">
						  			<div class="last_news_time" style="">21/3/15</div>
						  		</div>
						  	</div>
						</div>
		      		</div>
		      		<!-- 消息记录及聊天输入框 -->
		      		<div class="layui-col-xs8 layui-col-sm8 layui-col-md8 message_log_code">
		      			<!-- 顶部标题 -->
		      			<div class="layui-row now_chat_user">
		      				<div class="now_chat_user_info">
		      					<span class="now_chat_user_nickname">汽车俱乐部</span>
		      					<span class="now_chat_user_icon">
		      						<a onclick="chat_setting(this)"><i class="layui-icon layui-icon-more"></i></a>
		      					</span>
		      				</div>
		      			</div>
		      			<!-- 聊天记录 -->
		      			<div class="layui-row message_log">
		      				<div class="message_log_child_div">
	      						<!-- <div class="layui-card message">
								  	<div class="layui-card-header send_time">11:30</div>
								  	<div class="layui-card-header layui-inline other_user_headpic">
								  		<div class="user_headpic_div">
								  			<img src="public/images/headpic/self.jpg">
								  		</div>
								  	</div>
								  	<div class="layui-card-body layui-inline other_user_content" style="">
								    	卡片式面板面板通常用于非白色背景色的主体内<br>
								    	从而映衬出边框投影
								  	</div>
								</div>


								<div class="layui-card message">
								  	<div class="layui-card-header send_time">11:30</div>
								  	<div class="self_headpic_and_content">
								  		<div class="layui-inline del_message">
									  		<a class="layui-icon layui-icon-delete"></a>
									  	</div>
								  		<div class="layui-card-body layui-inline self_user_content" style="">
									    	卡片式面板面板通常用于非白色背景色的主体内<br>
									    	从而映衬出边框投影
									  	</div>
									  	<div class="layui-card-header layui-inline self_user_headpic">
									  		<div class="user_headpic_div">
									  			<img src="public/images/headpic/self.jpg">
									  		</div>
									  	</div>
								  	</div>
								</div> -->
								
		      				</div>
		      			</div>
		      			<!-- 内容输入区域 -->
		      			<div class="layui-row">
		      				<div class="content_input">
		      					<textarea id="demo" style="display: none;"></textarea>
		      					<div class="send_btn">
		      						<button type="button" class="layui-btn" id="send_btn_sub">发送</button>
		      					</div>
		      				</div>
		      			</div>
		      		</div>
		      		<!-- 聊天房间功能模块设置以及群成员列表 -->
		      		<div class="chat_room_setting" style="display: flex;float: right;display: none;">
		      			<ul class="layui-nav layui-nav-tree layui-nav-side">
		      				<table class="layui-table">
		      				  	<tbody>
								    <tr>
								      	<td>1</td>
								      	<td>2</td>
								      	<td>3</td>
								      	<td>4</td>
								    </tr>
								</tbody>
		      				</table>
		      			</ul>
		      		</div>
		      	</div>
		    </div>
	  	</div>
	</div>
</body>
<style type="text/css">
	.layui-layer-msg {
		border-radius: 10px;
		background-color: #1E9FFF;
	}
	.chat_room_setting .layui-nav-side {
		margin-top: 50px;
    	height: 700px;
    	left: unset;
    	background-color: #f2f2f2;
    	border: 1px solid #d2d2d2;
	}
	.chat_room_setting .layui-table {
		margin: 0;
	}
	.chat_room_setting .layui-table tr {
		text-align: center;
    	height: 70px;
	}
</style>
</html>
<script type="text/javascript" src="public/expands/layui/layui.all.js"></script>
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script type="text/javascript">
	//浏览器访问地址示例：http://socket.test/socket/app/chat.html?uid=1，uid表示用户id
	var layedit = layui.layedit,
		$ = layui.jquery,
		url = layui.url(),
		param = url.search,
		timer, //定时器
		user_id = param.uid;
	layedit.set({
	  	uploadImage: {
	    	url: 'upload.php', //接口url
	  	}
	});

  	var newlayedit = layedit.build('demo', {
  		height: 110,
  		tool: ['face', 'image']
  	}); //建立编辑器
  	let	readyState = 0; //websocket连接状态


  	if (! "WebSocket" in window) {
        layer.msg('您的浏览器不支持 WebSocket!');
    }

    //连接服务端
    // const ws = new WebSocket('ws://127.0.0.1:8081');
    const ws = new WebSocket('ws://10.3.141.169:8081');

    //点击按钮断开连接
   	$(".close_websocket").click(function () {
    	ws.close();
    });
    /**
     * readyState  返回当前 WebSocket 的链接状态
     * 0 连接中  1连接成功可以通讯  2连接正在关闭  3连接已关闭或者没有链接成功
     */
    ws.onopen = function(evt) { 
        readyState = ws.readyState;
        if (readyState != 1) alert('连接失败'); 
        var data = {user_id, 'type' : 'online'};
        sendMsg(data);
    };
   
    //接收消息
    ws.onmessage = function(evt) {
    	// console.log(evt.data);
    	let val = JSON.parse(evt.data);
    	switch (val.type) {
    		case 'online': //上线
    			layer.msg(val.content,{
    				area: '300px',
    				offset: 't',
    				time : 1000,
    			});
    			console.log(val.content);
    			break;
    		case 'offline'://下线
    			layer.msg(val.content,{
    				area: '300px',
    				offset: 't',
    				time : 1000,
    			});
    			console.log(val.content);
    			break;
    		case 'heartbeats'://开启心跳检测
    			//开启心跳检测
    			check_heartbeats(5000);
    			break;
    		case 'withdraw': //消息撤回
    			let message_id = val.message_id;
    			$('.'+message_id).remove();
    			break;
    		case 'broadcast': //广播
    			
    			break;
    		case 'chat':
    			$(".message_log_child_div").append(html.other_message(val.content,val.message_id));
    			break;
    	}
    };
    //心跳检测
    const check_heartbeats = (m = 1000) => {
    	timer = setTimeout(function () {
			let text = {'type' : 'heartbeats', 'content' : '检测连接状态'};
			// let text = moment().unix();
			sendMsg(text);
		}, m);
    }

    ws.onclose = (event) => {
    	layer.msg('网络连接失败',{
			area: '300px',
			offset: 't',
			time : 1000,
		});
    }

    ws.onerror = (event) => layer.msg(event);
  
   	//发送消息
   	send_btn_sub.onclick = function () {
   		if (ws.readyState != 1) return layer.msg('websocket连接出错');
   		let content = layedit.getContent(newlayedit),
   			message_id = user_id + '_' +moment().valueOf(),
   			field = {user_id, content, 'type' : 'chat', 'chat_type' : 'group_chat', message_id};
   		sendMsg(field);
   		$(".message_log_child_div").append(html.self_message(content,message_id));
   		layedit.setContent(newlayedit,'')
   	}
    /**
     * 将数据转为json并发送
     * @param msg
     */
    function sendMsg(msg) {
    	
        var res = JSON.stringify(msg);
        ws.send(res);
    }
    //给自己发的消息添加删除按钮(鼠标移入事件)
    function mouseover(self) {
    	if ($(self).children().is('.del_message') == false) {
    		let code = html.del_message();
    		$(self).prepend(code);
    	}

    }
    //将删除按钮删除(鼠标移出事件)
    function mouseleave (self) {
    	if ($(self).children().is('.del_message') == true) {
    		$(self).children(".del_message").remove();
    	}
    }
    //消息撤回
    function del_message (self) {
    	let message_id = $(self).parent().data('id'),
    	data = {'type' : 'withdraw', user_id, message_id};
    	sendMsg(data);
    	$("."+message_id).remove();
    };
    //当前聊天房间设置
    function chat_setting (self) {
    	$(".chat_room_setting").toggle("slow");
    }	
    
    const html = {
    	time : moment().format('Y/M/d h:mm:ss'),
    	//自己发送的消息
    	self_message (msg,message_id) {
    		let code = `<div class="layui-card message ${message_id}">
						  	<div class="layui-card-header send_time">${moment().format('Y/M/d h:mm:ss')}</div>
						  	<div class="self_headpic_and_content" data-id = "${message_id}" onmouseover = "mouseover(this)" onmouseleave = "mouseleave(this)">
						  		<div class="layui-card-body layui-inline self_user_content">
							    	${msg}
							  	</div>
							  	<div class="layui-card-header layui-inline self_user_headpic">
							  		<div class="user_headpic_div">
							  			<img src="public/images/headpic/self.jpg">
							  		</div>
							  	</div>
						  	</div>
						</div>`;
			return code;
    	},
    	//别人发送的消息
    	other_message (msg, message_id) {
    		let code = `<div class="layui-card message ${message_id}" data-id = "${message_id}">
						  	<div class="layui-card-header send_time">${moment().format('Y/M/d h:mm:ss')}</div>
						  	<div class="layui-card-header layui-inline other_user_headpic">
						  		<div class="user_headpic_div">
						  			<img src="public/images/headpic/self.jpg">
						  		</div>
						  	</div>
						  	<div class="layui-card-body layui-inline other_user_content">
						    	${msg}
						  	</div>
						</div>`;
			return code;
    	},
    	//删除消息图标
    	del_message () {
    		let code = `<div class="layui-inline del_message" onclick = "del_message(this)">
					  		<a class="layui-icon layui-icon-delete"></a>
					  	</div>`;
    		return code;
    	},
    };
</script>